package com.imooc.reader.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.reader.entity.*;
import com.imooc.reader.service.BookService;
import com.imooc.reader.service.CategoryService;
import com.imooc.reader.service.EvaluationService;
import com.imooc.reader.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BookController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BookService bookService;

    @Autowired
    private EvaluationService evaluationService;

    @Autowired
    private MemberService memberService;

    @GetMapping("/all")
    public ModelAndView showIndex() {
        ModelAndView modelAndView = new ModelAndView("/index");
        List<Category> list = categoryService.selectAll();
        modelAndView.addObject("categortList", list);
        return modelAndView;
    }

    @GetMapping("/book")
    @ResponseBody
    public IPage<Book> selectBook(Long categoryId, String order, Integer p) {
        if (p == null) {
            p = 1;
        }
        IPage<Book> paging = bookService.paging(categoryId, order, p, 10);
        return paging;
    }


    @GetMapping("/book/{id}")
    @ResponseBody
    public ModelAndView showDetail(@PathVariable("id") Long id, HttpSession session) {

        Book book = bookService.selectById(id);
        List<Evaluation> evaluationList = evaluationService.selectBookId(id);
        //获取当前登录用户的id
        Member loginMember = (Member) session.getAttribute("loginMember");
        ModelAndView modelAndView = new ModelAndView("a");
        if (loginMember != null) {
            //获取这个id的阅读状态
            MemberReadState memberReadState = memberService.selectStateById(loginMember.getMemberId(), id);
            modelAndView.addObject("memberReadState", memberReadState);
        }

        modelAndView.addObject("book", book);
        modelAndView.addObject("evaluationList", evaluationList);
        return modelAndView;
    }
}
